<script setup lang="ts">
import type { CodeMateModule } from '@/apis/code/codeMateApi'
import type { DataAction } from '@/components/DataForm/types'
import { inject, onMounted, reactive } from 'vue'
import { codeMateModuleApi } from '@/apis/code/codeMateApi'
import { useEditForm } from '@/components/DataForm/useEditForm'
import { codeModuleFields } from './codeMate'
import CodeModelTable from './CodeModelTable.vue'

const { data } = defineProps<{ data: CodeMateModule }>()
const emits = defineEmits(['remove'])

const {
  editFormData,
  submitEditForm,
  EditForm,
} = useEditForm<CodeMateModule>({
  editFields: codeModuleFields.filter(f => f.name !== 'id' && f.name !== 'priority'),
})

const api = codeMateModuleApi
const loadProjectData = inject<() => Promise<void>>('loadProjectData')
const clickTreeNode = inject<(id: number) => void>('clickTreeNode')
const actions = reactive <Record<string, DataAction>>({
  create: {
    label: '创建',
    type: 'primary',
    authCode: 'code:mate:module:create',
    click: async () => await submitEditForm('新增', api.create),
    success: async (data) => {
      loadProjectData && await loadProjectData()
      clickTreeNode && clickTreeNode(data.id)
    },
  },
  modify: {
    label: '保存',
    type: 'primary',
    authCode: 'code:mate:module:modify',
    click: async () => await submitEditForm('编辑', api.modify),
    success: loadProjectData,
  },
  remove: {
    label: '删除',
    type: 'danger',
    authCode: 'code:mate:project:remove',
    confirm: '删除不可恢复，请谨慎确认',
    click: async data => await api.remove(data.id),
    success: async () => {
      loadProjectData && await loadProjectData()
      emits('remove')
    },
    message: true,
  },
})
onMounted(() => editFormData.value = data)
</script>

<template>
  <div class="flex flex-row justify-end">
    <data-button v-if="editFormData.id !== undefined" v-model="editFormData" :action="actions.remove" />
    <data-button v-if="editFormData.id !== undefined" v-model="editFormData" :action="actions.modify" />
    <data-button v-if="editFormData.id === undefined" v-model="editFormData" :action="actions.create" />
  </div>

  <EditForm />

  <CodeModelTable
    v-if="editFormData.modelList && editFormData.id"
    :data="editFormData.modelList"
    :parent-id="editFormData.id"
  />
</template>
